package com.ljh.lottery.service.activitystatus.operator;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ljh.lottery.mapper.ActivityUserMapper;
import com.ljh.lottery.pojo.dataobject.ActivityUserDO;
import com.ljh.lottery.service.dto.ConvertActivityStatusDTO;
import com.ljh.lottery.service.enums.ActivityUserStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author: Themberfue
 * @date: 2025/4/17 10:40
 * @description:
 */
@Component
public class UserOperator extends AbstractActivityOperator {
    @Autowired
    ActivityUserMapper activityUserMapper;

    @Override
    public Integer sequence() {
        return 1;
    }

    @Override
    public Boolean needConvert(ConvertActivityStatusDTO convertActivityStatusDTO) {
        // TODO 1. 校验参数
        Long activityId = convertActivityStatusDTO.getActivityId();
        List<Long> userIds = convertActivityStatusDTO.getUserIds();
        ActivityUserStatusEnum activityUserStatusEnum = convertActivityStatusDTO.getTargetUserStatus();
        if (null == activityId
                || CollectionUtils.isEmpty(userIds)
                || null == activityUserStatusEnum) {
            return false;
        }

        // TODO 2. 检验其是否需要扭转状态
        QueryWrapper<ActivityUserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                    .eq(ActivityUserDO::getActivityId, activityId)
                    .in(ActivityUserDO::getUserId, userIds);
        List<ActivityUserDO> activityUserDOS = activityUserMapper.selectList(queryWrapper);

        if (CollectionUtils.isEmpty(activityUserDOS)) {
            return false;
        }

        for (ActivityUserDO activityUserDO: activityUserDOS) {
            if (activityUserDO.getStatus()
                    .equalsIgnoreCase(activityUserStatusEnum.name())) {
                return false;
            }
        }
        return true;
    }

    @Override
    public Boolean convert(ConvertActivityStatusDTO convertActivityStatusDTO) {
        try {
            UpdateWrapper<ActivityUserDO> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda()
                    .set(ActivityUserDO::getStatus, convertActivityStatusDTO.getTargetUserStatus().name())
                    .in(ActivityUserDO::getUserId, convertActivityStatusDTO.getUserIds())
                    .eq(ActivityUserDO::getActivityId, convertActivityStatusDTO.getActivityId());
            activityUserMapper.update(updateWrapper);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
